package com.bdqn.t330.ch11.controller;


import ch.qos.logback.core.net.SyslogOutputStream;
import com.bdqn.t330.ch11.entity.Role;
import com.bdqn.t330.ch11.servcie.RoleService;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Resource
    RoleService roleService;

    @RequestMapping("/getrolelist")
    @ResponseBody
    public Object getRoleList() {
        return roleService.getRoleList();
    }

    @RequestMapping("/list")
    public Object list(Model model,
                          @RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageIndex,
                          @RequestParam(value = "usrName", required = false, defaultValue = "") String usrName,
                          @RequestParam(value = "roleId", required = false, defaultValue = "0") Long roleId,
                          @RequestParam(value = "formDate", required = false) Date formDate,
                          @RequestParam(value = "endDate", required = false) Date endDate) {
        System.out.println("formDate:" + formDate);
        System.out.println("endDate" + endDate);

        Pageable pageable = PageRequest.of(pageIndex - 1, 2);
        Map<String, Object> map = new HashMap<>();
        map.put("formDate", formDate);
        map.put("endDate", endDate);

        Page<Role> page = roleService.getListService(map, pageable);

        model.addAttribute("page", page);
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("formDate", formDate);
        model.addAttribute("endDate", endDate);
        return "/role/list";
    }


    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm"), true));
    }


}
